package generator.dao.impl;

import cn.hutool.db.handler.BeanHandler;
import cn.hutool.db.handler.BeanListHandler;
import cn.hutool.db.sql.SqlExecutor;
import generator.dao.ITableDao;
import generator.model.Table;
import generator.util.JdbcUtils;

import java.sql.Connection;
import java.sql.SQLException;
import java.util.List;

/**
 * <p>
 *
 * </p>
 *
 * @author angel.bin@aliyun.com
 * @since 2020-10-05 13:36
 */
public class TableDaoImpl implements ITableDao {

    @Override
    public List<Table> selectTables() throws SQLException {
        Connection connection = JdbcUtils.getConnection();
        String sql =
                "select table_name name, table_comment comment, create_time createTime, update_time updateTime,auto_increment autoIncrement " +
                        "from " +
                        "information_schema.tables " +
                        "where " +
                        "table_schema = (select database())";
        List<Table> tables = SqlExecutor.query(connection, sql, BeanListHandler.create(Table.class));
        JdbcUtils.close();
        return tables;
    }

    @Override
    public Table selectTable(String tableName) throws SQLException {
        Connection connection = JdbcUtils.getConnection();
        String sql =
                "select table_name name, table_comment comment, create_time createTime, update_time updateTime,auto_increment autoIncrement " +
                        "from " +
                        "information_schema.tables " +
                        "where " +
                        "table_schema = (select database()) " +
                        "and table_name = ?";
        Table table = SqlExecutor.query(connection, sql, BeanHandler.create(Table.class), tableName);
        JdbcUtils.close();
        return table;
    }

}
